package consapi

import (
	"fmt"
	"net/http"
	"time"
)

// Event 事件
type Event struct {
	Eid     string      `json:"eid" bson:"eid"`
	Action  string      `json:"action" bson:"action"`
	Etype   string      `json:"etype" bson:"etype"`
	From    string      `json:"from" bson:"from"`
	OccTime time.Time   `json:"occTime" bson:"occTime"`
	Data    interface{} `json:"data" bson:"data"`
}

// CreateHandler 创建一个handler
func CreateHandler(buffCnt int) (http.HandlerFunc, <-chan *Event) {
	sh := CreateEventConsServerHandler(buffCnt)
	return func(resp http.ResponseWriter, req *http.Request) {
		sh.ServeHTTP(resp, req)
	}, sh.Recieve()
}

// CreateEventConsServerHandler 创建一个ServerHandler
func CreateEventConsServerHandler(buffCnt int) EventConsServerHandler {
	return &eventConsHandler{
		buffCnt: buffCnt,
	}
}

// EventConsServerHandler 事件消费者服务Handler
type EventConsServerHandler interface {
	http.Handler
	Recieve() <-chan *Event
}

type eventConsHandler struct {
	recv    chan *Event
	buffCnt int
}

const (
	msgError = `{"msg":"解码失败:"}%s`
)

func (s eventConsHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	evt, err := ParseEventRequest(req)
	if err != nil {
		resp.WriteHeader(500)
		fmt.Fprintf(resp, msgError, err.Error())
		slog.Warnf("解码失败:%s", err.Error())
		return
	}
	s.sendEvent(evt)
}

func (s *eventConsHandler) Recieve() <-chan *Event {
	if s.recv == nil {
		s.recv = make(chan *Event, s.buffCnt)

	}
	return s.recv
}
func (s *eventConsHandler) sendEvent(evt *Event) {
	defer func() {
		if err := recover(); err != nil {
			slog.Warn("接收事件通道已经关闭，不能在处理事件")
		}
	}()
	if s.recv != nil {
		s.recv <- evt
	}
}
